package com.zhangji.springcloud.controller;

import com.zhangji.springcloud.pojo.Dept;
import com.zhangji.springcloud.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Description: 提供Restful服务
 * @Author: Zhang Ji
 * @Date: 2021/6/22 20:45
 * Created by IntelliJ IDEA.
 */
@RestController
public class DeptController {

    @Autowired
    private DeptService deptService;

    /**
     * 获取配置信息
     */
    @Autowired
    private DiscoveryClient discoveryClient;

    @PostMapping("/dept/add")
    public boolean addDept(@RequestBody Dept dept){
        return deptService.addDept(dept);
    }

    @GetMapping("/dept/get/{id}")
    public Dept queryDeptById(@PathVariable("id") Long id){
        return deptService.queryDeptById(id);
    }

    @GetMapping("/dept/queryAll")
    public List<Dept> queryAll(){
        return deptService.queryAll();
    }


    /**
     * @Description: 获取application.yml中配置的实例信息
     * @return discoveryClient
     */
    @GetMapping("/dept/discovery")
    public Object discovery(){

        // 获取微服务实例的列表
        List<String> services = discoveryClient.getServices();
        System.out.println("获取微服务列表:"+services);

        // 通过ApplicationName获取具体微服务实例
        List<ServiceInstance> instances = discoveryClient.getInstances("SPRINGCLOUD-PROVIDER-DEPT-8001HAHA");
        for (ServiceInstance instance : instances) {
            System.out.println(
                    instance.getHost()+"\t"+
                            instance.getPort()+"\t"+
                            instance.getUri()+"\t"+
                            instance.getInstanceId()
                    );
        }

        return this.discoveryClient;

    }

}
